import 'dart:convert';

/// 评论列表请求模型
class CommentListRequest {
  final double latitude;
  final double longitude;
  final double radius;
  final int limit;
  final String timestamp;

  CommentListRequest({
    required this.latitude,
    required this.longitude,
    this.radius = 50.0,
    this.limit = 50,
    required this.timestamp,
  });

  Map<String, dynamic> toJson() {
    return {
      'latitude': latitude,
      'longitude': longitude,
      'radius': radius,
      'limit': limit,
      'timestamp': timestamp,
    };
  }

  factory CommentListRequest.fromJson(Map<String, dynamic> json) {
    return CommentListRequest(
      latitude: json['latitude']?.toDouble() ?? 0.0,
      longitude: json['longitude']?.toDouble() ?? 0.0,
      radius: json['radius']?.toDouble() ?? 50.0,
      limit: json['limit']?.toInt() ?? 50,
      timestamp: json['timestamp'] ?? '',
    );
  }
}

/// 评论数据模型
class CommentData {
  final int commentId;
  final String commentTitle;
  final String commentContent;
  final List<String> commentImages;
  final List<String> commentCategory;
  final List<String> commentTags;
  final String commentLocation;
  final double longitude;
  final double latitude;
  final String commentPublishTime;
  final List<String> shoppingImages;
  final int publisherId;
  final String publisherAvatar;
  final String publisherNickname;
  final String publisherSignature;
  final List<String> publisherTags;
  final int publisherPoints;
  final int likeCount;
  final int commentCount;
  final int shareCount;
  final List<String> status;
  final Map<String, dynamic>? extraData;
  final double distance;
  final int minutesAgo;
  final double weightScore;
  final int isLiked;

  CommentData({
    required this.commentId,
    required this.commentTitle,
    required this.commentContent,
    this.commentImages = const [],
    this.commentCategory = const [],
    this.commentTags = const [],
    this.commentLocation = '',
    this.longitude = 0.0,
    this.latitude = 0.0,
    this.commentPublishTime = '',
    this.shoppingImages = const [],
    required this.publisherId,
    this.publisherAvatar = '',
    required this.publisherNickname,
    this.publisherSignature = '',
    this.publisherTags = const [],
    this.publisherPoints = 0,
    this.likeCount = 0,
    this.commentCount = 0,
    this.shareCount = 0,
    this.status = const [],
    this.extraData,
    this.distance = 0.0,
    this.minutesAgo = 0,
    this.weightScore = 0.0,
    this.isLiked = 0,
  });

  factory CommentData.fromJson(Map<String, dynamic> json) {
    return CommentData(
      commentId: json['commentId']?.toInt() ?? 0,
      commentTitle: json['commentTitle'] ?? '',
      commentContent: json['commentContent'] ?? '',
      commentImages: _parseStringList(json['commentImages']),
      commentCategory: _parseStringList(json['commentCategory']),
      commentTags: _parseStringList(json['commentTags']),
      commentLocation: json['commentLocation'] ?? '',
      longitude: json['longitude']?.toDouble() ?? 0.0,
      latitude: json['latitude']?.toDouble() ?? 0.0,
      commentPublishTime: json['commentPublishTime'] ?? '',
      shoppingImages: _parseStringList(json['shoppingImages']),
      publisherId: json['publisherId']?.toInt() ?? 0,
      publisherAvatar: json['publisherAvatar'] ?? '',
      publisherNickname: json['publisherNickname'] ?? '',
      publisherSignature: json['publisherSignature'] ?? '',
      publisherTags: _parseStringList(json['publisherTags']),
      publisherPoints: json['publisherPoints']?.toInt() ?? 0,
      likeCount: json['likeCount']?.toInt() ?? 0,
      commentCount: json['commentCount']?.toInt() ?? 0,
      shareCount: json['shareCount']?.toInt() ?? 0,
      status: _parseStringList(json['status']),
      extraData: json['extraData'] is Map<String, dynamic> ? json['extraData'] : null,
      distance: json['distance']?.toDouble() ?? 0.0,
      minutesAgo: json['minutes_ago']?.toInt() ?? 0,
      weightScore: json['weight_score']?.toDouble() ?? 0.0,
      isLiked: json['is_liked']?.toInt() ?? 0,
    );
  }

  /// 解析字符串列表，支持JSON字符串或直接的List格式
  static List<String> _parseStringList(dynamic value) {
    if (value == null) return [];
    
    if (value is List) {
      return value.map((e) => e.toString()).toList();
    }
    
    if (value is String) {
      try {
        if (value.startsWith('[') && value.endsWith(']')) {
          final decoded = jsonDecode(value);
          if (decoded is List) {
            return decoded.map((e) => e.toString()).toList();
          }
        }
      } catch (e) {
        // 如果解析失败，尝试作为单个字符串处理
        return [value];
      }
    }
    
    return [];
  }

  Map<String, dynamic> toJson() {
    return {
      'commentId': commentId,
      'commentTitle': commentTitle,
      'commentContent': commentContent,
      'commentImages': commentImages,
      'commentCategory': commentCategory,
      'commentTags': commentTags,
      'commentLocation': commentLocation,
      'longitude': longitude,
      'latitude': latitude,
      'commentPublishTime': commentPublishTime,
      'shoppingImages': shoppingImages,
      'publisherId': publisherId,
      'publisherAvatar': publisherAvatar,
      'publisherNickname': publisherNickname,
      'publisherSignature': publisherSignature,
      'publisherTags': publisherTags,
      'publisherPoints': publisherPoints,
      'likeCount': likeCount,
      'commentCount': commentCount,
      'shareCount': shareCount,
      'status': status,
      'extraData': extraData,
      'distance': distance,
      'minutes_ago': minutesAgo,
      'weight_score': weightScore,
      'is_liked': isLiked,
    };
  }
}

/// 分页信息模型
class PaginationInfo {
  final int total;
  final int page;
  final int limit;
  final int totalPages;

  PaginationInfo({
    required this.total,
    required this.page,
    required this.limit,
    required this.totalPages,
  });

  factory PaginationInfo.fromJson(Map<String, dynamic> json) {
    return PaginationInfo(
      total: json['total']?.toInt() ?? 0,
      page: json['page']?.toInt() ?? 1,
      limit: json['limit']?.toInt() ?? 10,
      totalPages: json['total_pages']?.toInt() ?? 1,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'total': total,
      'page': page,
      'limit': limit,
      'total_pages': totalPages,
    };
  }

  @override
  String toString() {
    return 'PaginationInfo(total: $total, page: $page, limit: $limit, totalPages: $totalPages)';
  }
}

/// 评论列表响应模型
class CommentListResponse {
  final String status;
  final String? message;
  final List<CommentData> data;
  final PaginationInfo? pagination;

  CommentListResponse({
    required this.status,
    this.message,
    this.data = const [],
    this.pagination,
  });

  /// 判断请求是否成功
  bool get isSuccess => status == 'success';

  /// 获取错误信息
  String get errorMessage => message ?? '未知错误';

  /// 获取评论数量
  int get commentCount => data.length;

  factory CommentListResponse.fromJson(Map<String, dynamic> json) {
    return CommentListResponse(
      status: json['status'] ?? 'error',
      message: json['message'],
      data: json['data'] != null 
          ? (json['data'] as List).map((item) => CommentData.fromJson(item)).toList()
          : [],
      pagination: json['pagination'] != null 
          ? PaginationInfo.fromJson(json['pagination'])
          : null,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'status': status,
      'message': message,
      'data': data.map((item) => item.toJson()).toList(),
      'pagination': pagination?.toJson(),
    };
  }
}

/// 评论详情请求模型
class CommentDetailRequest {
  final int commentId;
  final String? userId;
  final String timestamp;

  CommentDetailRequest({
    required this.commentId,
    this.userId,
    required this.timestamp,
  });

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = {
      'commentId': commentId,
      'timestamp': timestamp,
    };
    
    if (userId != null) {
      data['userId'] = userId;
    }
    
    return data;
  }

  factory CommentDetailRequest.fromJson(Map<String, dynamic> json) {
    return CommentDetailRequest(
      commentId: json['commentId'] ?? 0,
      userId: json['userId']?.toString(),
      timestamp: json['timestamp'] ?? '',
    );
  }
}

/// 评论详情响应模型
class CommentDetailResponse {
  final String status;
  final String? message;
  final CommentDetailData? comment;
  final CommentUserData? user;

  CommentDetailResponse({
    required this.status,
    this.message,
    this.comment,
    this.user,
  });

  /// 判断请求是否成功
  bool get isSuccess => status == 'success';

  /// 获取错误信息
  String get errorMessage => message ?? '未知错误';
  
  /// 获取评论数据（为了保持兼容性）
  CommentDetailData? get data => comment;

  factory CommentDetailResponse.fromJson(Map<String, dynamic> json) {
    return CommentDetailResponse(
      status: json['status'] ?? 'error',
      message: json['message'],
      comment: json['comment'] != null ? CommentDetailData.fromJson(json['comment']) : null,
      user: json['user'] != null ? CommentUserData.fromJson(json['user']) : null,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'status': status,
      'message': message,
      'comment': comment?.toJson(),
      'user': user?.toJson(),
    };
  }
}

/// 评论详情数据模型
class CommentDetailData {
  final int commentId;
  final String commentTitle;
  final String commentContent;
  final List<String> commentImages;
  final List<String> commentCategory;
  final List<String> commentTags;
  final String commentLocation;
  final double longitude;
  final double latitude;
  final String commentPublishTime;
  final List<String> shoppingImages;
  
  // 发布者信息
  final int publisherId;
  final String publisherAvatar;
  final String publisherNickname;
  final String publisherSignature;
  final List<String> publisherTags;
  final int publisherPoints;
  
  // 统计信息
  final int likeCount;
  final int commentCount;
  final int shareCount;
  final int isLiked; // 当前用户是否已点赞
  
  // 状态和扩展数据
  final List<String> status;
  final Map<String, dynamic>? extraData;
  
  // 计算字段
  final double distance;
  final int minutesAgo;
  final double weightScore;

  CommentDetailData({
    required this.commentId,
    required this.commentTitle,
    required this.commentContent,
    required this.commentImages,
    required this.commentCategory,
    required this.commentTags,
    required this.commentLocation,
    required this.longitude,
    required this.latitude,
    required this.commentPublishTime,
    required this.shoppingImages,
    required this.publisherId,
    required this.publisherAvatar,
    required this.publisherNickname,
    required this.publisherSignature,
    required this.publisherTags,
    required this.publisherPoints,
    required this.likeCount,
    required this.commentCount,
    required this.shareCount,
    required this.isLiked,
    required this.status,
    this.extraData,
    required this.distance,
    required this.minutesAgo,
    required this.weightScore,
  });

  factory CommentDetailData.fromJson(Map<String, dynamic> json) {
    return CommentDetailData(
      commentId: json['commentId'] ?? 0,
      commentTitle: json['commentTitle'] ?? '',
      commentContent: json['commentContent'] ?? '',
      commentImages: _parseStringList(json['commentImages']),
      commentCategory: _parseStringList(json['commentCategory']),
      commentTags: _parseStringList(json['commentTags']),
      commentLocation: json['commentLocation'] ?? '',
      longitude: (json['longitude'] ?? 0.0).toDouble(),
      latitude: (json['latitude'] ?? 0.0).toDouble(),
      commentPublishTime: json['commentPublishTime'] ?? '',
      shoppingImages: _parseStringList(json['shoppingImages']),
      publisherId: json['publisherId'] ?? 0,
      publisherAvatar: json['publisherAvatar'] ?? '',
      publisherNickname: json['publisherNickname'] ?? '',
      publisherSignature: json['publisherSignature'] ?? '',
      publisherTags: _parseStringList(json['publisherTags']),
      publisherPoints: json['publisherPoints'] ?? 0,
      likeCount: json['likeCount'] ?? 0,
      commentCount: json['commentCount'] ?? 0,
      shareCount: json['shareCount'] ?? 0,
      isLiked: json['isLiked'] ?? 0,
      status: _parseStringList(json['status']),
      extraData: json['extraData'] is Map<String, dynamic> ? json['extraData'] : null,
      distance: (json['distance'] ?? 0.0).toDouble(),
      minutesAgo: json['minutes_ago'] ?? 0,
      weightScore: (json['weight_score'] ?? 0.0).toDouble(),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'commentId': commentId,
      'commentTitle': commentTitle,
      'commentContent': commentContent,
      'commentImages': commentImages,
      'commentCategory': commentCategory,
      'commentTags': commentTags,
      'commentLocation': commentLocation,
      'longitude': longitude,
      'latitude': latitude,
      'commentPublishTime': commentPublishTime,
      'shoppingImages': shoppingImages,
      'publisherId': publisherId,
      'publisherAvatar': publisherAvatar,
      'publisherNickname': publisherNickname,
      'publisherSignature': publisherSignature,
      'publisherTags': publisherTags,
      'publisherPoints': publisherPoints,
      'likeCount': likeCount,
      'commentCount': commentCount,
      'shareCount': shareCount,
      'isLiked': isLiked,
      'status': status,
      'extraData': extraData,
      'distance': distance,
      'minutes_ago': minutesAgo,
      'weight_score': weightScore,
    };
  }

  /// 工具方法：解析字符串列表，支持JSON字符串和List两种格式
  static List<String> _parseStringList(dynamic value) {
    if (value == null) return [];
    
    if (value is List) {
      return value.map((item) => item.toString()).toList();
    }
    
    if (value is String) {
      if (value.trim().isEmpty) return [];
      
      try {
        // 尝试解析JSON字符串
        final decoded = jsonDecode(value);
        if (decoded is List) {
          return decoded.map((item) => item.toString()).toList();
        }
      } catch (e) {
        // 如果不是JSON格式，直接返回包含该字符串的列表
        return [value];
      }
    }
    
    return [];
  }
}

/// 评论用户数据模型
class CommentUserData {
  final int userid;
  final String userPhone;
  final String? userEmail;
  final int userCode;
  final String username;
  final String userAvatarUrl;
  final Map<String, dynamic>? userData;
  final int userAge;
  final String userGender;
  final String userSignature;
  final List<String> userTags;
  final int userLikes;
  final int userFollowers;
  final int userPoints;
  final List<String> userHobbies;
  final String userCity;
  final List<String> userImgUrls;
  final String userFrequentPlaces;
  final String? userBirthday;
  final int userLevel;
  final String status;
  final Map<String, dynamic>? extraData;
  final String createdAt;
  final String? lastLogin;
  final String updatedAt;

  CommentUserData({
    required this.userid,
    required this.userPhone,
    this.userEmail,
    required this.userCode,
    required this.username,
    required this.userAvatarUrl,
    this.userData,
    required this.userAge,
    required this.userGender,
    required this.userSignature,
    required this.userTags,
    required this.userLikes,
    required this.userFollowers,
    required this.userPoints,
    required this.userHobbies,
    required this.userCity,
    required this.userImgUrls,
    required this.userFrequentPlaces,
    this.userBirthday,
    required this.userLevel,
    required this.status,
    this.extraData,
    required this.createdAt,
    this.lastLogin,
    required this.updatedAt,
  });

  factory CommentUserData.fromJson(Map<String, dynamic> json) {
    return CommentUserData(
      userid: json['userid'] ?? 0,
      userPhone: json['userPhone'] ?? '',
      userEmail: json['userEmail']?.toString(),
      userCode: json['userCode'] ?? 0,
      username: json['username'] ?? '',
      userAvatarUrl: json['userAvatarUrl'] ?? '',
      userData: json['userData'] is Map<String, dynamic> ? json['userData'] : null,
      userAge: json['userAge'] ?? 0,
      userGender: json['userGender'] ?? '',
      userSignature: json['userSignature'] ?? '',
      userTags: CommentDetailData._parseStringList(json['userTags']),
      userLikes: json['userLikes'] ?? 0,
      userFollowers: json['userFollowers'] ?? 0,
      userPoints: json['userPoints'] ?? 0,
      userHobbies: CommentDetailData._parseStringList(json['userHobbies']),
      userCity: json['userCity'] ?? '',
      userImgUrls: CommentDetailData._parseStringList(json['userImgUrls']),
      userFrequentPlaces: json['userFrequentPlaces'] ?? '',
      userBirthday: json['userBirthday']?.toString(),
      userLevel: json['userLevel'] ?? 0,
      status: json['status'] ?? '',
      extraData: json['extraData'] is Map<String, dynamic> ? json['extraData'] : null,
      createdAt: json['created_at'] ?? '',
      lastLogin: json['last_login']?.toString(),
      updatedAt: json['updated_at'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'userid': userid,
      'userPhone': userPhone,
      'userEmail': userEmail,
      'userCode': userCode,
      'username': username,
      'userAvatarUrl': userAvatarUrl,
      'userData': userData,
      'userAge': userAge,
      'userGender': userGender,
      'userSignature': userSignature,
      'userTags': userTags,
      'userLikes': userLikes,
      'userFollowers': userFollowers,
      'userPoints': userPoints,
      'userHobbies': userHobbies,
      'userCity': userCity,
      'userImgUrls': userImgUrls,
      'userFrequentPlaces': userFrequentPlaces,
      'userBirthday': userBirthday,
      'userLevel': userLevel,
      'status': status,
      'extraData': extraData,
      'created_at': createdAt,
      'last_login': lastLogin,
      'updated_at': updatedAt,
    };
  }
}